package com.chiemy.cardview;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.chiemy.cardview.manager.CommandManager;
import com.chiemy.cardview.util.DataHandlerUtils;
import com.chiemy.cardview.util.SPUtils;
import com.example.otalib.boads.Constant;
import com.example.otalib.boads.WorkOnBoads;
import com.hs.ble.BluetoothLeService;
import com.hs.ble.LeDeviceListAdapter;
import com.hs.ble.SampleGattAttributes;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OTAFragment extends Fragment implements OnClickListener {
    private static final int ENTER_OTA = 0;
    private static final int START_OTA = 1;
    public static String TAG = OTAFragment.class.getSimpleName();
    public static boolean DEBUG_OTA = true;
    public static boolean SEE_ORIGNAL_SEND_DATA = false;

    private TextView tv;
    private ListView lv;
    private Button down_btn;
    private Button scan_btn;
    private Button startOta;
    private TextView macAddress;
    private Button getMac;
    private Button findBand;
    private ProgressBar pb;
    private View root;
    private View view;
    private int APP_FILE_SELECT_CODE = 0;
    private int CONF_FILE_SELECT_CODE = 1;
    private int PATCH_FILE_SELECT_CODE = 2;
    private int USER_FILE_SELECT_CODE = 3;

    private Uri m_appfile_uri = null;
    private Uri m_conffile_uri = null;
    private Uri m_patchfile_uri = null;
    private Uri m_userfile_uri = null;
    private String tag = "OTAFragment";
    private Context context;

    private WorkOnBoads do_work_on_boads;

    public static final int MSG_BURN_APP_SUCCESS = 0x00;
    public static final int MSG_BURN_CFG_SUCCESS = 0x01;
    public static final int MSG_BURN_PATCH_SUCCESS = 0x02;
    public static final int MSG_OTA_COMPLETE = 0X04;
    public static final int MSG_FLASH_EMPTY = 0x05;
    public static final int MSG_HANDS_UP_FAILED = 0x08;
    public static final int MSG_OTA_FAILED = 0x09;
    public static final int MSG_DISCONNECT_BLE = 0x10;

    private boolean has_app = false;
    private boolean has_cfg = false;
    private boolean has_patch = false;
    private boolean has_user = false;
    private byte[] is_continue = new byte[1];

    private boolean support_encription = true;
    //ble
    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private static final long SCAN_PERIOD = 10000;
    private LeDeviceListAdapter mLeDeviceListAdapter;
    private ListView listView;
    public BluetoothLeService mBLE;
    private String mDeviceAddress;

    public static boolean mConnected = false;
    private List<BluetoothGattService> BluetoothGattServices;
    private Intent mBleService;

    public BluetoothGattCharacteristic ota_tx_dat_charac = null;
    public BluetoothGattCharacteristic ota_rx_dat_charac = null;

    public BluetoothGattCharacteristic ota_tx_cmd_charac = null;
    public BluetoothGattCharacteristic ota_rx_cmd_charac = null;
    /**
     *
     */
    public BluetoothGattCharacteristic wake_charac = null;

    private Thread mTransThread = null;
    private boolean mIsWorcking = false;
    private TextView useraddr;
    private TextView appaddr;
    private TextView patchaddr;
    private TextView confgaddr;
    private Button entry_btn;
    private EditText isptext;
    private String ispMac;
    private int setRssi;
    private Button auto_ota;


    Handler autoHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case ENTER_OTA:
                    Log.i(TAG,"ENTER_OTA");
                    mBluetoothAdapter.stopLeScan(mLeScanCallbackAuto);
                    mScanning = false;
                    //连接蓝牙 发送指令 进入ota

                    now_is_enter_ota = true;



                    mBLE.connect(address);


                    break;
                case START_OTA:
                    Log.i(TAG,"START_OTA");
                    mBluetoothAdapter.stopLeScan(mLeScanCallbackAuto);
                    mScanning = false;
                    //连接 Huntersun-BLE 开始ota

                    now_is_start_ota = true;


                    mBLE.connect(address);

                    break;
            }
        }
    };
    private String address;

    /**
     * 现在是处于进入ota的事件
     */
    private boolean now_is_enter_ota;
    /**
     * 现在是处于开始ota的事件
     */
    private boolean now_is_start_ota;
    private boolean auto_ota_open;


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.context = activity;
        this.mBLE = ((MainActivity) activity).mBLE;
        mBluetoothAdapter = ((MainActivity) activity).mBluetoothAdapter;
    }

    public OTAFragment() {

        do_work_on_boads = new WorkOnBoads(this.context, handler);
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @SuppressWarnings("deprecation")
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                down_btn.setText("Start Download");
                scan_btn.setText("Start Scan");
                mLeDeviceListAdapter.clear();
                mLeDeviceListAdapter.notifyDataSetChanged();

                getMac.setEnabled(true);
                startOta.setEnabled(true);

                // 自动ota

                if (now_is_enter_ota){
                    //进入ota

                    autoHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            CommandManager.getInstance(getActivity()).setFindBand();

                        }
                    },1500);

                    autoHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            CommandManager.getInstance(getActivity()).bootloader();

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            //进入ota的事件完成
                            now_is_enter_ota = false;
                            mBluetoothAdapter.startLeScan(mLeScanCallbackAuto);
                            mScanning = true;

                        }
                    },2000);


                }else if (now_is_start_ota){
                    //开始ota
                    autoHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            startOta();

                        }
                    },2000);

                }



            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {

                if (mBLE != null)
                    mBLE.close();
                Log.e("peng", "receiver disconnect");
                mConnected = false;
                down_btn.setText("Start Download");
                scan_btn.setText("Start Scan");
                entry_btn.setEnabled(false);
                down_btn.setEnabled(false);
                if (mIsWorcking) {
                    Toast.makeText(getActivity(), "The connection is lost while OTA is working!", Toast.LENGTH_SHORT)
                            .show();
                    mIsWorcking = false;
                }
                pb.setProgress(0);
                pb.setVisibility(ProgressBar.INVISIBLE);

                getMac.setEnabled(false);
                startOta.setEnabled(false);


                // 自动ota

                if (now_is_enter_ota){
                    Log.i(TAG,"now_is_enter_ota"+"--auto_ota_open: "+auto_ota_open);
                    //连接失败 ，略过，自动开始搜，连
                    if (auto_ota_open){
                        mBluetoothAdapter.startLeScan(mLeScanCallbackAuto);
                        mScanning = true;
                    }
                    //进入ota的事件完成
                    now_is_enter_ota = false;
                }else if (now_is_start_ota){
                    Log.i(TAG,"now_is_start_ota"+"--auto_ota_open: "+auto_ota_open);
                    //连接失败 或者 升级成功，自动开始搜，连
                    if (auto_ota_open) {
                        mBluetoothAdapter.startLeScan(mLeScanCallbackAuto);
                        mScanning = true;
                    }
                    //开始ota的事件完成
                    now_is_start_ota = false;

                }


            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                Log.i(TAG, "ACTION_GATT_SERVICES_DISCOVERED");
                // Show all the supported services and characteristics on the user interface.
                BluetoothGattServices = mBLE.getSupportedGattServices();
                String uuid = null;
                // Loops through available GATT Services.
                // TODO: 2018/3/7 java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference 
                for (BluetoothGattService gattService : BluetoothGattServices) {

                    List<BluetoothGattCharacteristic> gattCharacteristics =
                            gattService.getCharacteristics();
                    ArrayList<BluetoothGattCharacteristic> charas =
                            new ArrayList<BluetoothGattCharacteristic>();

                    // Loops through available Characteristics.
                    for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                        Log.e(TAG, "uuid:" + gattCharacteristic.getUuid().toString());
                        if (SampleGattAttributes.otas_tx_dat_uuid.equals(gattCharacteristic.getUuid().toString())) {
                            ota_tx_dat_charac = gattCharacteristic;
                            down_btn.setEnabled(true);
                            if ((ota_tx_dat_charac.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                                boolean res = mBLE.setCharacteristicNotification(
                                        gattCharacteristic, true);
                                if (res) {
                                    Log.i(tag, "Set Notify Success");

                                } else {
                                    Log.i(tag, "Notify failed!!");
                                    //Toast.makeText(getApplicationContext(), "Notify failed!!", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } else if (SampleGattAttributes.otas_rx_dat_uuid.equals(gattCharacteristic.getUuid().toString())) {
                            try {
                                Thread.sleep(350);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            ota_rx_dat_charac = gattCharacteristic;
                            if ((ota_rx_dat_charac.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {

                                boolean res = mBLE.setCharacteristicNotification(
                                        gattCharacteristic, true);
                                if (res) {
                                    Log.i(tag, "Set Notify Success");

                                } else {
                                    Log.i(tag, "Notify failed!!");
                                }
                            }
                        } else if (SampleGattAttributes.otas_rx_cmd_uuid.equals(gattCharacteristic.getUuid().toString())) {

                            ota_rx_cmd_charac = gattCharacteristic;
                            if ((ota_rx_cmd_charac.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                                boolean res = mBLE.setCharacteristicNotification(
                                        gattCharacteristic, true);
                                if (res) {
                                    Log.i(tag, "Set Notify Success");

                                } else {
                                    Log.i(tag, "Notify failed!!");
                                    //Toast.makeText(getApplicationContext(), "Notify failed!!", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } else if (SampleGattAttributes.otas_tx_cmd_uuid.equals(gattCharacteristic.getUuid().toString())) {
                            ota_tx_cmd_charac = gattCharacteristic;
                            if ((ota_tx_cmd_charac.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                                boolean res = mBLE.setCharacteristicNotification(
                                        gattCharacteristic, true);
                                if (res) {
                                    Log.i(tag, "Set Notify Success");

                                } else {
                                    Log.i(tag, "Notify failed!!");
                                }
                            }
                        } else if (SampleGattAttributes.otas_tx_ips_cmd_uuid.equals(gattCharacteristic.getUuid().toString())) {
                            ota_tx_cmd_charac = gattCharacteristic;
                            entry_btn.setEnabled(true);
                            if (ota_tx_cmd_charac.getProperties() == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
                                boolean res = mBLE.setCharacteristicNotification(ota_tx_cmd_charac, true);
                                if (res) {
                                    Log.i(tag, "Set Notify Success");

                                } else {
                                    Log.i(tag, "Notify failed!!");
                                }
                            }
                        } else if (SampleGattAttributes.otas_rx_ips_cmd_uuid.equals(gattCharacteristic.getUuid().toString())) {
                            ota_rx_cmd_charac = gattCharacteristic;
                            if (ota_rx_cmd_charac.getProperties() == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
                                boolean res = mBLE.setCharacteristicNotification(
                                        gattCharacteristic, true);
                                if (res) {
                                    Log.i(tag, "Set Notify Success");

                                } else {
                                    Log.i(tag, "Notify failed!!");
                                    //Toast.makeText(getApplicationContext(), "Notify failed!!", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } else if (SampleGattAttributes.WAKE_TX_CHAR_UUID.equals(gattCharacteristic.getUuid()
                        )) {
                            Log.i(TAG, "WAKE_TX_CHAR_UUID");
                            wake_charac = gattCharacteristic;
                            if (wake_charac.getProperties() == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
                                //收取我们手环发过来的消息
                                boolean res = mBLE.setCharacteristicNotification(
                                        gattCharacteristic, true);
                                if (res) {
                                    Log.i(TAG, "enableTXNotification Success");

                                } else {
                                    Log.i(TAG, "enableTXNotification failed!!");
                                }

                            }

                        }
                    }
                }
                //ShowGattServices(mBLE.getSupportedGattServices());
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                //read peer char
                byte[] byteArrayExtra = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (byteArrayExtra == null) {
                    return;
                }
                String s = DataHandlerUtils.bytesToHexStr(byteArrayExtra);
                List<Integer> data = DataHandlerUtils.bytesToArrayList(byteArrayExtra);

                Log.d(TAG, "接收的数据：" + s);
                if (s != null) {
                    if (data.get(0) == 1) {
                        String[] strings = s.split(" ");

                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = strings.length - 1; i >= 2; i--) {
                            Log.i(TAG, strings[i]);
                            stringBuilder.append(strings[i]);
                            if (i != 2) {
                                stringBuilder.append(":");
                            }
                        }
                        ispMac = stringBuilder.toString().toUpperCase();
                        Log.i(TAG, "ispMac：" + ispMac);
                        macAddress.setText(ispMac);
                    } else if (data.get(0) == 0xAB && data.get(4) == 0x28 && data.get(5) == 0x80) {
                        String[] strings = s.split(" ");
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = strings.length - 1; i >= 9; i--) {
                            Log.i(TAG, strings[i]);
                            stringBuilder.append(strings[i]);
                            if (i != 9) {
                                stringBuilder.append(":");
                            }
                        }
                        ispMac = stringBuilder.toString().toUpperCase();
                        Log.i(TAG, "ispMac：" + ispMac);
                        macAddress.setText(ispMac);

                    }
                }


            } else if (BluetoothLeService.ACTION_GATT_CHARACTER_NOTIFY.equals(action)) {
                intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
            }
            // HS OTA
            else if (BluetoothLeService.OTA_RX_DAT_ACTION.equals(action)) {
                Log.i(TAG, "OTA_RX_DAT_ACTION");
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.ARRAY_BYTE_DATA);
                if (data != null) {
                    do_work_on_boads.setBluetoothNotifyData(data, Constant.DATCHARC);
                }
            }
            //OTA CMD
            else if (BluetoothLeService.OTA_RX_CMD_ACTION.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.ARRAY_BYTE_DATA);
                if (data != null) {
                    do_work_on_boads.setBluetoothNotifyData(data, Constant.CMDCHARC);
                }
            } //OTA isp CMD
            else if (BluetoothLeService.OTA_RX_ISP_CMD_ACTION.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.ARRAY_BYTE_DATA);
                isptext.setText(Utils.bytesToHexString(data).replace(" ", "").substring(2));
                do_work_on_boads.EntryIspMoudle(Constant.MSG_ARG1_ENTRY_ISP);
            }
        }
    };


    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBLE = ((BluetoothLeService.LocalBinder) service).getService();
            Log.i(tag, "in onServiceConnected!!!");
            if (!mBLE.initialize()) {
                Log.e(tag, "Unable to initialize Bluetooth");
                ((Activity) context).finish();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBLE = null;
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CHARACTER_NOTIFY);
        intentFilter.addAction(BluetoothLeService.OTA_RX_CMD_ACTION);
        intentFilter.addAction(BluetoothLeService.OTA_RX_DAT_ACTION);
        intentFilter.addAction(BluetoothLeService.OTA_RX_ISP_CMD_ACTION);
        return intentFilter;
    }

    @Override
    public void onResume() {
        super.onResume();
        setRssi = SPUtils.getInt(getActivity(), SPUtils.SET_RSSI, -55);
        boolean auto = SPUtils.getBoolean(getActivity(), SPUtils.AUTO_OTA, false);

        auto_ota.setVisibility(auto ? View.VISIBLE : View.INVISIBLE);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        auto_ota = (Button) view.findViewById(R.id.auto_ota);
        auto_ota.setOnClickListener(this);

    }


    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.ota_frag_layout, container, false);
        initUI(root);
        mLeDeviceListAdapter = new LeDeviceListAdapter((Activity) context);
        //listView = new ListView(context);
        lv.setAdapter(mLeDeviceListAdapter);

        //ble init
        if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(context, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            ((Activity) context).finish();
        }

        final BluetoothManager bluetoothManager =
                (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(context, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            ((Activity) context).finish();
            return root;
        }
        //
        mBluetoothAdapter.enable();


        //start broadcast-service
        Intent i = new Intent(context, BluetoothLeService.class);
        context.startService(i);
        context.bindService(i, mServiceConnection, Context.BIND_AUTO_CREATE);
        mBleService = i;
        context.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        SampleGattAttributes.initalerpaly();
        return root;
    }


    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg == null)
                return;

            Message msg2 = msg;
            if (msg2.what == Constant.MSG_WHAT_READ_PART) {
                int addr = msg2.arg1;
                int length = msg2.arg2;
                switch ((Integer) msg2.obj) {
                    case Constant.APPTYPE:
                        appaddr.setText("0x" + Integer.toHexString(addr));
                        break;
                    case Constant.CONFGTYPE:
                        confgaddr.setText("0x" + Integer.toHexString(addr));
                        break;
                    case Constant.PATCHTYPE:
                        patchaddr.setText("0x" + Integer.toHexString(addr));
                        break;
                }

            } else if (msg2.what == 10) {
                if (msg2.obj != null) {
                    String str = (String) msg2.obj;
                    Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
                }
            }
            switch (msg2.arg1) {
                case MSG_BURN_APP_SUCCESS:

                    break;

                case MSG_DISCONNECT_BLE:
                    down_btn.setEnabled(false);
                    isptext.setText("isp Addr");
                    break;
                case MSG_BURN_CFG_SUCCESS:

                    break;
                case MSG_BURN_PATCH_SUCCESS:

                    break;
                case MSG_FLASH_EMPTY:
                    dialog("The Board flash is empty, Are you sure to erase flash now!!!");
                    break;
                // 需要向dat的蓝⽛牙特征发送数据的handle
                case Constant.MSG_ARG1_SEND_OTA_DATA:

                    int pos = 0;
                    int len = msg2.arg2;
                    int tmp = len % 20;
                    byte[] senddat = (byte[]) msg2.obj;
                    boolean res;
                    if (ota_tx_dat_charac == null) {
                        Toast.makeText(getActivity(), "OTA has not discover the right character!", Toast.LENGTH_SHORT)
                                .show();
                        down_btn.setEnabled(false);
                        scan_btn.setText("Start Scan");
                        return;
                    }
                    for (int i = 0; i < len / 20; i++) {
                        byte[] packet_data = new byte[20];
                        System.arraycopy(senddat, pos, packet_data, 0, 20);

                        if (mConnected == true && mBLE != null) {
                            if (SEE_ORIGNAL_SEND_DATA) {
                                File sd = Environment.getExternalStorageDirectory();
                                String path = sd.getPath() + "/" + "HSOTAsendLog.txt";
                                Utils op = new Utils();
                                op.writeSDFileAppend(path, "[HS_OTA Send]-> " + Utils.bytesToHexString(packet_data) + "\r\n");
                            }
                            Log.i("DEBUG_OTA", "ota send lenth:" + packet_data.length);
                            res = ota_tx_dat_charac.setValue(packet_data);
                            if (!res) {
                                i--;
                                Log.i(tag, "setValue() failed!!!");
                                continue;
                            }
                            ota_tx_dat_charac.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                            res = mBLE.writeCharacteristic(ota_tx_dat_charac);
                            if (!res) {
                                i--;
                                Log.i(tag, "writeCharacteristic() failed!!!");
                                continue;
                            }
                            pos = pos + 20;
                        }
                    }
                    if (tmp != 0) {
                        byte[] packet_data = new byte[tmp];
                        System.arraycopy(senddat, pos, packet_data, 0, tmp);

                        if (mConnected == true && mBLE != null) {
                            if (SEE_ORIGNAL_SEND_DATA) {
                                File sd = Environment.getExternalStorageDirectory();
                                String path = sd.getPath() + "/" + "HSOTAsendLog.txt";
                                Utils op = new Utils();
                                op.writeSDFileAppend(path, "[HS_OTA Send]-> " + Utils.bytesToHexString(packet_data) + "\r\n");
                            }
                            Log.i("DEBUG_OTA", "ota send lenth:" + packet_data.length);
                            res = ota_tx_dat_charac.setValue(packet_data);
                            if (!res) {
                                Log.i(tag, "setValue() failed!!!");
                            }

                            ota_tx_dat_charac.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                            res = mBLE.writeCharacteristic(ota_tx_dat_charac);
                            if (!res)
                                Log.i(tag, "writeCharacteristic() failed!!!");

                        }
                    }
                    break;

                case MSG_OTA_COMPLETE:
                    mIsWorcking = false;
                    Toast.makeText(getActivity(), "OTA has done and success!", Toast.LENGTH_SHORT)
                            .show();
                    if (mConnected && mBLE != null) {
                        mBLE.disconnect();
                        mBLE.close();
                    }
                    down_btn.setEnabled(false);
                    scan_btn.setText("Start Scan");
                    down_btn.setText("Start Download");
                    pb.setProgress(0);
                    pb.setVisibility(ProgressBar.INVISIBLE);
                    break;
                //返回⽂文件最⼤大值的handler⽤用于设置进度条
                case Constant.MSG_ARG1_PROGRESS_BAR_MAX:
                    pb.setVisibility(View.VISIBLE);
                    int len1 = msg2.arg2;
                    pb.setMax(len1);
                    break;
                // 设置进度条的进度时的handler
                case Constant.MSG_ARG1_PROGRESS_BAR_UPDATA:
                    int len2 = msg2.arg2;
                    pb.setProgress(len2);
                    break;
                case MSG_HANDS_UP_FAILED:
                    Toast.makeText(getActivity(), "Hands up to the boads failed before OTA!", Toast.LENGTH_SHORT)
                            .show();
                    pb.setProgress(0);
                    pb.setVisibility(ProgressBar.INVISIBLE);
                    down_btn.setEnabled(true);
                    scan_btn.setText("Start Scan");
                    down_btn.setText("iStart Download");
                    pb.setProgress(0);
                    pb.setVisibility(ProgressBar.INVISIBLE);
                    break;
                case MSG_OTA_FAILED:
                    if (msg.obj != null) {
                        String toaststr = (String) msg.obj;
                        Toast.makeText(getActivity(), toaststr, Toast.LENGTH_SHORT)
                                .show();
                        pb.setProgress(0);
                        pb.setVisibility(ProgressBar.INVISIBLE);
                        down_btn.setEnabled(false);
                        scan_btn.setText("Start Scan");
                        down_btn.setText("Start Download");
                    }
                    break;
                // 设置加密传输失败的handler
                case Constant.MSG_ARG1_OTA_ENCRPT_KEY_FAILED:
                    Toast.makeText(getActivity(), "OTA exchange key please try again!", Toast.LENGTH_SHORT).show();
                    pb.setProgress(0);
                    pb.setVisibility(ProgressBar.INVISIBLE);
                    down_btn.setEnabled(true);
                    scan_btn.setText("Start Scan");
                    down_btn.setText("Start Download");
                    break;
                // 需要向cmd的蓝⽛牙特征发送数据的handler
                case Constant.MSG_ARG1_SEND_OTA_CMD: {
                    int pos1 = 0;
                    int len3 = msg2.arg2;
                    int tmp1 = len3 % 20;
                    byte[] sendcmd = (byte[]) msg2.obj;
                    boolean res1 = false;
                    if (ota_tx_cmd_charac == null) {
                        Toast.makeText(getActivity(), "OTA has not discover the right character!", Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                    for (int i = 0; i < len3 / 20; i++) {
                        if (i % 2 == 0) {
                            try {
                                Thread.sleep(8);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        byte[] packet_data = new byte[20];
                        System.arraycopy(sendcmd, pos1, packet_data, 0, 20);

                        if (mConnected == true && mBLE != null) {
                            ota_tx_cmd_charac.setValue(packet_data);
                            res1 = mBLE.writeCharacteristic(ota_tx_cmd_charac);
                            if (!res1) {
                                i--;
                                Log.i(tag, "Write value failed!!!");
                                continue;
                            }
                            pos1 = pos1 + 20;
                            Log.i(tag, packet_data.toString());
                        }

                    }
                    if (tmp1 != 0) {
                        try {
                            Thread.sleep(8);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        byte[] packet_data = new byte[tmp1];
                        System.arraycopy(sendcmd, pos1, packet_data, 0, tmp1);

//                        Log.e("peng","cmd data:"+Utils.bytesToHexString(packet_data));
                        if (mConnected == true && mBLE != null) {
                            ota_tx_cmd_charac.setValue(packet_data);
                            res1 = mBLE.writeCharacteristic(ota_tx_cmd_charac);
                            if (!res1)
                                Log.i(tag, "Write value failed!!!");
                            Log.i(tag, packet_data.toString());
                        }
                    }
                }
                break;
            }
        }
    };


    private void initUI(final View root) {
        root.setClickable(true);
        root.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        appaddr = (TextView) root.findViewById(R.id.app_addr);
        patchaddr = (TextView) root.findViewById(R.id.patch_addr);
        confgaddr = (TextView) root.findViewById(R.id.confg_addr);
        isptext = (EditText) root.findViewById(R.id.ispaddr);

        tv = (TextView) root.findViewById(R.id.textView);
        useraddr = (TextView) root.findViewById(R.id.user_data_addr);
        lv = (ListView) root.findViewById(R.id.list_device);
        down_btn = (Button) root.findViewById(R.id.downloadBtn);
        entry_btn = (Button) root.findViewById(R.id.entryIsp);

        scan_btn = (Button) root.findViewById(R.id.scanBtn);
        getMac = (Button) root.findViewById(R.id.getMac);
        findBand = (Button) root.findViewById(R.id.findBand);
        startOta = (Button) root.findViewById(R.id.startOta);
        macAddress = (TextView) root.findViewById(R.id.macAddress);
        down_btn.setEnabled(false);
        entry_btn.setEnabled(false);
        pb = (ProgressBar) root.findViewById(R.id.progressBar);
        pb.setVisibility(ProgressBar.VISIBLE);

        //
        root.findViewById(R.id.applicationBtn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showFileChooser(APP_FILE_SELECT_CODE);
            }

        });


        //
        root.findViewById(R.id.configurationBtn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showFileChooser(CONF_FILE_SELECT_CODE);
            }

        });

        //
        root.findViewById(R.id.patchBtn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showFileChooser(PATCH_FILE_SELECT_CODE);
            }

        });

        root.findViewById(R.id.userBtn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showFileChooser(USER_FILE_SELECT_CODE);
            }

        });

        //scan
        root.findViewById(R.id.scanBtn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mConnected && mBLE != null) {
                    mBLE.disconnect();
                    mBLE.close();
                }
                down_btn.setEnabled(false);
                entry_btn.setEnabled(false);
                down_btn.setText("Start Download");
                scanLeDevice(true);
                Log.i(TAG, "Start scan");
            }

        });

        // entryISP
        root.findViewById(R.id.entryIsp).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                do_work_on_boads.EntryIspMoudle(Constant.MSG_ARG1_ISP_ADDR);
                entry_btn.setEnabled(false);
            }
        });


        //download
        root.findViewById(R.id.downloadBtn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                pb.setVisibility(ProgressBar.VISIBLE);
                down_btn.setEnabled(false);
                scan_btn.setText("StopDown");

                //开始ota
                startOta();
            }

        });

        getMac.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CommandManager.getInstance(getActivity()).bootloaderMac();
            }
        });
        findBand.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CommandManager.getInstance(getActivity()).setFindBand();
            }
        });

        startOta.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CommandManager.getInstance(getActivity()).bootloader();

            }
        });

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
                if (device == null) return;
                if (mScanning) {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    mScanning = false;
                }
                mDeviceAddress = device.getAddress();
                if (mBLE == null)
                    return;
                boolean res = mBLE.connect(mDeviceAddress);
                if (!res)
                    Log.i(tag, "call ble connect failed");
                mLeDeviceListAdapter.clear();
                mLeDeviceListAdapter.notifyDataSetChanged();
                down_btn.setText("Connecting...");

            }

        });

        root.findViewById(R.id.button).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                m_appfile_uri = null;
                m_conffile_uri = null;
                m_patchfile_uri = null;
                m_userfile_uri = null;

                has_user = false;
                has_app = false;
                has_cfg = false;
                has_patch = false;

                if (mScanning)
                    scanLeDevice(false);

                if (mConnected && mBLE != null) {
                    mBLE.disconnect();
                    mBLE.close();
                }
                down_btn.setEnabled(false);
                entry_btn.setEnabled(false);

                EditText et = (EditText) root.findViewById(R.id.applicationText);
                et.setText("");

                et = (EditText) root.findViewById(R.id.configurationText);
                et.setText("");

                et = (EditText) root.findViewById(R.id.patchText);
                et.setText("");

                et = (EditText) root.findViewById(R.id.user_data_text);
                et.setText("");

                appaddr.setText("");
                confgaddr.setText("");
                patchaddr.setText("");
                useraddr.setText("");
                isptext.setText("isp Addr");

                root.setClickable(false);
                ViewPropertyAnimator.animate(root)
                        .rotationY(-90).setDuration(200)
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                root.clearAnimation();
                                //root.setVisibility(View.GONE);
                                view.setEnabled(true);
                            }
                        });
            }
        });

        if (view == null) {
            return;
        }

        ViewHelper.setRotationY(view, 0);

        if (root != null) {
            ViewHelper.setRotationY(root, -90);
            root.setVisibility(View.VISIBLE);
        }

        ViewPropertyAnimator.animate(view).rotationY(90)
                .setDuration(300).setListener(null)
                .setInterpolator(new AccelerateInterpolator());

        if (root != null) {
            ViewPropertyAnimator.animate(root)
                    .rotationY(0).setDuration(200).setStartDelay(300)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            ViewHelper.setRotationY(view, 0);
                        }
                    });
        }


        //设置
        TextView setting = (TextView) root.findViewById(R.id.setting);
        setting.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
            }
        });

    }

    /**
     * 开始ota
     */
    private void startOta() {
        Log.d(TAG,"startOta------");
        if (mIsWorcking) {
            return;
        }
        Log.d(TAG,"startOta1------");

        mIsWorcking = true;
        mTransThread = new Thread(new Runnable() {

            @Override
            public void run() {
                int response;
                // 设置为加密传输
                do_work_on_boads.setEncrypt(false);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 判断是否有文件数据
                has_app = (m_appfile_uri != null);
                has_cfg = (m_conffile_uri != null);
                has_patch = (m_patchfile_uri != null);
                has_user = (m_userfile_uri != null);
                if (!has_app && !has_cfg && !has_patch && !has_user)
                    return;

                int readPartresponse = do_work_on_boads.ReadPart(Constant.PATCHTYPE);
                do_work_on_boads.ReadPart(Constant.APPTYPE);
                do_work_on_boads.ReadPart(Constant.CONFGTYPE);

                if (readPartresponse < 0) {
                    Message msg = Message.obtain();
                    msg.what = 10;
                    msg.obj = "read part error!";
                    handler.sendMessage(msg);
                }

                if (has_user) {
                    String addr = useraddr.getText().toString();
                    if (addr.length() <= 0) {
                        Looper.prepare();
                        Toast.makeText(context, "Addr的值不能为空！！！", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }

                    byte[] tmp_read;
                    Utils op = new Utils();
                    String file_path = GetPathFromUri4kitkat.getPath(context, m_userfile_uri);
                    try {
                        tmp_read = op.readSDFile(file_path);
                    } catch (IOException e) {
                        e.printStackTrace();
                        mIsWorcking = false;
                        return;
                    }

                    response = do_work_on_boads.WriteUserData(tmp_read, addr);
                    SendFileRseponse(response);
                }

                //burn app
                if (has_app) {
                    byte[] tmp_read;
                    Utils op = new Utils();
                    String file_path = GetPathFromUri4kitkat.getPath(context, m_appfile_uri);
                    try {
                        //do_work_on_boads.app_buf = op.readSDFile(file_path);
                        tmp_read = op.readSDFile(file_path);

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        mIsWorcking = false;
                        return;
                    }
                    response = do_work_on_boads.LoadBinary(tmp_read, Constant.APPTYPE);
                    SendFileRseponse(response);
                }

                //burn configuration
                if (has_cfg) {
                    byte[] tmp_read;
                    Utils op = new Utils();
                    String file_path = GetPathFromUri4kitkat.getPath(context, m_conffile_uri);
                    try {
                        tmp_read = op.readSDFile(file_path);
                    } catch (IOException e) {
                        e.printStackTrace();
                        mIsWorcking = false;
                        return;
                    }
                    response = do_work_on_boads.LoadBinary(tmp_read, Constant.CONFGTYPE);
                    SendFileRseponse(response);
                }

                //burn patch
                if (has_patch) {
                    byte[] tmp_read;
                    Utils op = new Utils();
                    String file_path = GetPathFromUri4kitkat.getPath(context, m_patchfile_uri);
                    try {
                        tmp_read = op.readSDFile(file_path);
                    } catch (IOException e) {
                        e.printStackTrace();
                        mIsWorcking = false;
                        return;
                    }
                    response = do_work_on_boads.LoadBinary(tmp_read, Constant.PATCHTYPE);
                    SendFileRseponse(response);
                }
                // 复位硬件
                do_work_on_boads.ResetTarget();

                Message msg = Message.obtain();
                msg.arg1 = MSG_DISCONNECT_BLE;
                handler.sendMessage(msg);

            }
        });//.start();
        mTransThread.start();
    }

    private void SendFileRseponse(int response) {
        String detail;
        switch (response) {
            case Constant.NORESPONSEERROR:
                detail = "OTA is not response!";
                break;
            case Constant.INVALIDPARAMETERERROR:
                detail = "Send parameter error!";
                break;
            case Constant.FILETOBIGERROR:
                detail = "Too large a file to send!";
                break;
            case Constant.LOADBINARYFILEERROR:
                detail = "Send load binary file error!";
                break;
            case Constant.EXECFORMATERROR:
                detail = "Error sending upgrade package format!";
                break;
            case Constant.USERADDRERROR:
                detail = "User Addr error !";
                break;
            case 0:
                detail = "OTA has been successful!";
                break;
            default:
                detail = "OTA Send failed!!!";
                if (mConnected && mBLE != null)
                    mBLE.disconnect();
                break;
        }
        Message msg = new Message();
        msg.arg1 = MSG_OTA_FAILED;
        msg.obj = detail;
        handler.sendMessage(msg);
        mIsWorcking = false;
    }

    public void show(final View view, Bundle bundle) {
        view.setEnabled(false);
        this.view = view;

        ViewHelper.setRotationY(view, 0);

        if (root != null) {
            ViewHelper.setRotationY(root, -90);
            root.setVisibility(View.VISIBLE);
        }

        ViewPropertyAnimator.animate(view).rotationY(90)
                .setDuration(300).setListener(null)
                .setInterpolator(new AccelerateInterpolator());

        if (root != null) {
            ViewPropertyAnimator.animate(root)
                    .rotationY(0).setDuration(200).setStartDelay(300)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            ViewHelper.setRotationY(view, 0);
                        }
                    });
        }

    }

    private void dialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                (MainActivity) context);
        builder.setTitle("提示");
        builder.setMessage(message);
        builder.setCancelable(false);
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                synchronized (is_continue) {
                    is_continue[0] = 1;
                    is_continue.notifyAll();
                }
                dialog.dismiss();
            }

        });


        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                synchronized (is_continue) {
                    is_continue[0] = 0;
                    is_continue.notifyAll();
                }

                dialog.dismiss();

            }

        });
        builder.show();

    }

    /**
     * 调用文件选择软件来选择文件
     **/
    private void showFileChooser(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
                    requestCode);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(getActivity(), "请安装文件管理器", Toast.LENGTH_SHORT)
                    .show();
        }
    }


    /**
     * 根据返回选择的文件，来进行上传操作
     **/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (resultCode == Activity.RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String file_path = uri.getEncodedPath();
            file_path = uri.getLastPathSegment();
            //file_path = uri.getPathSegments();
            file_path = uri.getPath();
            String fileName = file_path.substring(file_path.lastIndexOf("/") + 1);
            Toast.makeText(getActivity(), uri.toString(), Toast.LENGTH_SHORT)
                    .show();
            if (requestCode == APP_FILE_SELECT_CODE) {
                m_appfile_uri = uri;//.toString();
                EditText et = (EditText) root.findViewById(R.id.applicationText);
                et.setText("");
                et.setText(fileName);
            } else if (requestCode == CONF_FILE_SELECT_CODE) {
                m_conffile_uri = uri;//.toString();
                EditText et = (EditText) root.findViewById(R.id.configurationText);
                et.setText("");
                et.setText(fileName);
            } else if (requestCode == PATCH_FILE_SELECT_CODE) {
                m_patchfile_uri = uri;//.toString();
                EditText et = (EditText) root.findViewById(R.id.patchText);
                et.setText("");
                et.setText(fileName);
            } else if (requestCode == USER_FILE_SELECT_CODE) {
                m_userfile_uri = uri;
                EditText et = (EditText) root.findViewById(R.id.user_data_text);
                et.setText(fileName);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            mLeDeviceListAdapter.clear();
            mLeDeviceListAdapter.notifyDataSetChanged();
            // Stops scanning after a pre-defined scan period.
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    //invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        //invalidateOptionsMenu();
    }


    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
                    if (scanRecord == null) {
                        return;
                    }

                    //根据一些特征过滤蓝牙
//                    if (!tmp1.contains("HS")) {
//                        return;
//                    }
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (rssi < setRssi) {
//                                Log.i(TAG, "信号太弱--" + rssi + "--" + setRssi);
                                return;
                            }
                            mLeDeviceListAdapter.addDevice(device);
                            mLeDeviceListAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };


    @Override
    public void onDestroy() {
        super.onDestroy();
        context.unregisterReceiver(mGattUpdateReceiver);
        context.unbindService(mServiceConnection);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.auto_ota:
                Log.i(TAG, "auto_ota");

                has_app = (m_appfile_uri != null);
                has_cfg = (m_conffile_uri != null);
                has_patch = (m_patchfile_uri != null);
                has_user = (m_userfile_uri != null);
                if (!has_app && !has_cfg && !has_patch && !has_user){
                    Toast.makeText(getActivity(),"请选择文件!",Toast.LENGTH_SHORT).show();
                    return;
                }


                //开始扫描


                if (auto_ota.getText().toString().equals("自动OTA")) {
                    Log.i(TAG,"自动OTA");
                    if (!mScanning){
                        mBluetoothAdapter.startLeScan(mLeScanCallbackAuto);
                        mScanning = true;
                    }

                    auto_ota.setText("停止自动OTA");

                    auto_ota_open = true;


                }else if (auto_ota.getText().toString().equals("停止自动OTA")) {
                    Log.i(TAG,"停止自动OTA");

                    if (mScanning){
                        mBluetoothAdapter.stopLeScan(mLeScanCallbackAuto);
                        mScanning = false;
                    }

                    auto_ota.setText("自动OTA");

                    auto_ota_open = false;
                }



                break;
        }
    }


    private BluetoothAdapter.LeScanCallback mLeScanCallbackAuto =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
                    if (scanRecord == null) {
                        return;
                    }

                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (rssi < setRssi) {
                                Log.i(TAG, "信号太弱--" + rssi + "--" + setRssi);
                                return;
                            }
                            String name = device.getName();
                            address = device.getAddress();
                            Log.i(TAG, name + "- -" + address);

                            if (TextUtils.isEmpty(name)||TextUtils.isEmpty(address)) {
                                Log.w(TAG,"name or address null");
                                return;
                            }


                            String deviceName = SPUtils.getString(getActivity(), SPUtils.DEVICE_NAME, "");

                            if (deviceName.equals(name)) {
                                autoHandler.sendEmptyMessage(ENTER_OTA);

                            }

                            if ("Huntersun-BLE".equals(name)){
                                autoHandler.sendEmptyMessage(START_OTA);

                            }


                        }
                    });
                }
            };
}
